package com.moonstar.config;


import com.moonstar.exception.AuthException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @author:
 * @desc: 登录拦截器
 * @Time: 2023/1/15  10:16
 */

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("loginUser");
        if (user == null) {
            // 如果是ajax请求，抛异常
            String XRequested = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(XRequested)) {
                throw new AuthException("请登录");
            } else {
                // 如果是普通请求，跳转到登录页面
                response.setContentType("text/html");
                PrintWriter pw = response.getWriter();
                pw.write("<script>window.parent.location.href='/';</script>");
                return false;
            }
        }
        //默认放过
        return true;
    }

    /***
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("执行了拦截器的postHandle方法");
    }

    /***
     * 整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("执行了拦截器的afterCompletion方法");
    }

}
